package com.sanpu.kxe.business.trade.presenter;

import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;

import com.sanpu.kxe.R;
import com.sanpu.kxe.business.main.provider.IMainProvider;
import com.sanpu.kxe.business.member.provider.IMemberProvider;
import com.sanpu.kxe.business.trade.bean.PayCollectionOutput;
import com.sanpu.kxe.business.trade.bean.PayLimit;
import com.sanpu.kxe.business.trade.bean.PaymentOutput;
import com.sanpu.kxe.business.trade.contract.ChoosePayDetailsContract;
import com.sanpu.kxe.business.trade.contract.TradeConfig;
import com.sanpu.kxe.business.trade.model.TradeModel;
import com.sanpu.kxe.business.trade.provider.TradeOpenProvider;
import com.sanpu.kxe.common.enums.PayEvent;
import com.sanpu.kxe.common.enums.PayType;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.common.interfaces.DialogViewListener;
import com.sanpu.kxe.module.dialog.GlobalDialog;
import com.sanpu.kxe.rxservice.RxError;
import com.sanpu.kxe.utils.DateUtils;
import com.sanpu.kxe.utils.DialogUtil;
import com.sanpu.kxe.utils.PublicProviderUtil;
import com.sanpu.kxe.utils.ToastUtil;

import java.math.BigDecimal;
import java.util.List;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：收款选择支付渠道
 * Created by 薛勇军 on 2019/3/1.
 */

public class ChoosePayDetailsPresenter implements ChoosePayDetailsContract.Presenter {

    private ChoosePayDetailsContract.View mView;

    private CompositeSubscription mSubscription;

    private String reqAmount, reqType;

    private String chkSts;

    private PayType mPayType = null;

    public ChoosePayDetailsPresenter(ChoosePayDetailsContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void initData(String reqAmount, String reqType, String chkSts) {
        this.reqAmount = reqAmount;
        this.reqType = reqType;
        this.chkSts = chkSts;
        if (TextUtils.equals(TradeConfig.GATHERING_PAY, reqType)) {
            collectionList(TradeConfig.RECEIVABLESTYPE_MERCHANT);
        } else if (TextUtils.equals(TradeConfig.GATHERING_QUICKPAY, reqType)) {
            collectionList(TradeConfig.RECEIVABLESTYPE_PERSON);
        }
    }

    /**
     * 收款渠道列表
     *
     * @param collectionType PERSION:个人 SCAN：扫码
     */
    private void collectionList(String collectionType) {
        mView.showLoadingDialog(true);
        Subscription subscription = TradeModel.getInstance().appCnlConfList(collectionType)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<PayCollectionOutput>>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(List<PayCollectionOutput> payCollectionOutputs) {
                        if (payCollectionOutputs != null && payCollectionOutputs.size() > 0) {
//                            List<PayCollectionOutput> payListData = new ArrayList<>();
//                            List<PayCollectionOutput> quickListData = new ArrayList<>();
//                            for (PayCollectionOutput retDatBean:payCollectionOutputs) {
//                                try {
//                                    if (TextUtils.equals(CommonConfig.INTERFACETYPE_API, retDatBean.getInterfaceType()))
//                                        quickListData.add(retDatBean);
//                                    else
//                                        payListData.add(retDatBean);
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                            }
                            mView.showListDataView(payCollectionOutputs);
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void onItemClickListener(final PayCollectionOutput collectionOutput) {
        try {
            if (collectionOutput == null) return;
            if (collectionOutput.isNeedPicture()
                    && !TextUtils.equals(CommonConfig.AUTHEN_PASS, chkSts)) {
                String btnText = "", contentText = "";
                switch (chkSts) {
                    case CommonConfig.AUTHEN_AUDIT:
                        btnText = "确定";
                        contentText = "您的实名认证正在审核中，请稍后";
                        break;
                    case CommonConfig.AUTHEN_NOPASS:
                        btnText = "重新补全";
                        contentText = "您的补全资料审核失败，请重新补全审核通过后才能开启扫码收款";
                        break;
                    case CommonConfig.AUTHEN_NOCOMPLETION:
                        btnText = "补全资料";
                        contentText = "该通道需要补全资料才能进行交易";
                        break;
                }
                DialogUtil.getInstance().dialogNoTitletTwoBtnHaveCallBack(mView.getContext(),
                        contentText, "取消", btnText,
                        new DialogViewListener() {
                            @Override
                            public void btnRightConfirm() {
                                if (!TextUtils.equals(CommonConfig.AUTHEN_AUDIT, chkSts))
                                    openCertificationActivity();
                            }

                            @Override
                            public void btnLeftCancel() {

                            }
                        });
                return;
            }
            if (TextUtils.equals("DISABLE", collectionOutput.getEnableStatus())) {
                GlobalDialog dialog = new GlobalDialog(mView.getContext())
                        .content(collectionOutput.getDisableReason())
                        .headerIcon(R.drawable.img_fail_result);
                dialog.show();
                return;
            }
            String payTime = collectionOutput.getTradeStartTime() + "," + collectionOutput.getTradeEndTime();
            if (!DateUtils.isSupportPaymentTime(payTime)) {
                String[] tranTm = payTime.split(",");
                new GlobalDialog(mView.getContext())
                        .content("暂时不能支付，支付时间段：(" + tranTm[0] + "-" + tranTm[1] + ")。").show();
                return;
            }
            try {
                mPayType = PayType.valueOf(collectionOutput.getBusinessType());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (mPayType == null) {
                ToastUtil.showTextViewPrompt("该支付方式暂不可用，请尝试其他");
                return;
            }
            //方便测试，调试的时候最低付款为1毛钱
            PayLimit payLimit = new PayLimit(collectionOutput.getMinTradeAmount(), collectionOutput.getMaxTradeAmount());
            BigDecimal amt = new BigDecimal(reqAmount);
            if (amt.compareTo(payLimit.getMin()) == -1) {
                ToastUtil.showTextViewPrompt(mPayType.getTitle() + "最低为￥" + payLimit.getMin());
                return;
            }
            if (amt.compareTo(payLimit.getMax()) == 1) {
                ToastUtil.showTextViewPrompt(mPayType.getTitle() + "最高为￥" + payLimit.getMax() + "单笔");
                return;
            }
            final String amount = amt.toString();
            if (TextUtils.equals("T1", collectionOutput.getSettleType())) {//T1
                String remark;
                if (TextUtils.equals(TradeConfig.GATHERING_QUICKPAY, reqType)) {
                    remark = "您收款的资金将在下一个工作日转入您的结算卡中（节假日不到账），若需要实时到账，请选择【秒刷秒到】";
                } else {
                    remark = "您收款的资金将在下一个工作日转入您的结算卡中（节假日不到账），若需要实时到账，请选择个人收款里面的【秒刷秒到】";
                }
                DialogUtil.getInstance().dialogExistTitleTwoBtnHaveCallBack(
                        mView.getContext(), "温馨提示", remark, "重新收款", "继续收款",
                        new DialogViewListener() {
                            @Override
                            public void btnRightConfirm() {
                                onPay(amount, collectionOutput);
                            }

                            @Override
                            public void btnLeftCancel() {

                            }
                        });
                return;
            }
            onPay(amount, collectionOutput);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 支付
     */
    private void onPay(String amount, PayCollectionOutput collectionOutput) {
        if (mPayType == PayType.QQ_WAP || mPayType == PayType.ALIPAY_WAP) {
            String messageTitle = mPayType == PayType.QQ_WAP ? "正在启动QQ,准备支付..." : "正在启动支付宝,准备支付...";
            mView.showLoadingDialog(false, messageTitle);
            Subscription subscription = TradeModel.getInstance().userPayment(amount, mPayType.getValue(),
                    PayEvent.CONSUME.getValue(), null, null)
                    .subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<PaymentOutput>() {
                        @Override
                        public void onCompleted() {
                            mView.dismissLoadingDialog();
                        }

                        @Override
                        public void onError(Throwable e) {
                            mView.dismissLoadingDialog();
                            if (e instanceof RxError) {
                                mView.showErrorText(e);
                            } else {
                                ToastUtil.showTextViewPrompt("支付失败！");
                            }
                        }

                        @Override
                        public void onNext(PaymentOutput paymentOutput) {
                            Uri uri = Uri.parse(paymentOutput.getCodeUrl());
                            Intent it = new Intent(Intent.ACTION_VIEW, uri);
                            mView.getContext().startActivity(it);
                        }
                    });
            mSubscription.add(subscription);
        } else {
            if (TextUtils.equals(TradeConfig.GATHERING_QUICKPAY, reqType)) {
                onSetupPayActivity(amount, mPayType, collectionOutput);
            } else {
                TradeOpenProvider.getInstance().openPaymentQRcodeActivity(
                        mView.getContext(), amount, mPayType, collectionOutput.getAppCnlConfId());
            }
        }
    }

    /**
     * 跳转到快捷支付
     */
    private void onSetupPayActivity(String amt, PayType payType, PayCollectionOutput collectionOutput) {
        if (TextUtils.equals(CommonConfig.INTERFACETYPE_H5, collectionOutput.getInterfaceType())) {
            TradeOpenProvider.getInstance()
                    .openQuickPayWebActivity(mView.getContext(), amt, payType, collectionOutput);
        } else {
            TradeOpenProvider.getInstance()
                    .openFastPayComfirmActivity(mView.getContext(), amt, payType, collectionOutput);
        }
    }

    /**
     * 去认证
     */
    private void openCertificationActivity() {
        IMainProvider mainProvider = PublicProviderUtil.getProvider(IMainProvider.class);
        if (mainProvider != null) {
            mainProvider.openCertificationActivity(mView.getContext(), false);
        }
    }

    @Override
    public void openMembershipDetailsActivity() {
        IMemberProvider provider = PublicProviderUtil.getProvider(IMemberProvider.class);
        if (provider != null) {
            provider.openMemberLevelsListActivity(mView.getContext());
        }
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
